//#define _XOPEN_SOURCE 600
#define _BSD_SOURCE
#include <unistd.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pty.h>

#if defined(__CYGWIN__)
// Workaround for Cygwin, which is missing cfmakeraw. Pasted from man page.
void cfmakeraw(struct termios *termios_p)
{
    termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
    termios_p->c_oflag &= ~OPOST;
    termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
    termios_p->c_cflag &= ~(CSIZE|PARENB);
    termios_p->c_cflag |= CS8;
}
#endif


int main(int argc, char **argv)
{
	int masterFd;
	int slaveFd;
	
	struct termios termp;
	tcgetattr(0, &termp);
	cfmakeraw(&termp);
	
	printf("Opening pty\n");
	//openpty(&masterFd, &slaveFd, NULL, &termp, NULL);
	openpty(&masterFd, &slaveFd, NULL, NULL, NULL);
	printf("master=%i, slave=%i\n", masterFd, slaveFd);
	
	//tcsetattr(masterFd, TCSANOW, &termp);
	
	if(fork())
	{
		int bytesWritten = write(masterFd, "abcd\n", 5);
		printf("Wrote %i bytes to %i\n", bytesWritten, masterFd);
		sleep(1);
		
		//close(masterFd);
		
		printf("Reading back leftovers\n");
		while(1) {
			char buf[16];
			memset(buf, 0, 16);
			int bytesRead = read(slaveFd, buf, 15);
			printf("Read %i bytes\n", bytesRead);
			printf("leftover str=%s\n", buf);
		}
	}
	else
	{
		close(masterFd);
		
		printf("Reading from %i\n", slaveFd);
		char buf[16];
		memset(buf, 0, 16);
		int bytesRead = read(slaveFd, buf, 2);
		printf("Read %i bytes\n", bytesRead);
		printf("str=%s\n", buf);
		
		close(slaveFd);
	}
	
	return 0;
}

